#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量下载单词图片脚本
支持多种方法：
1. Unsplash API（推荐，需要API key）
2. Pixabay API（需要API key）
3. 占位图生成（不需要API，但图片简单）
4. 使用爬虫从免费图片网站下载

需要安装: pip install requests pillow
"""

import requests
import os
import time
from PIL import Image, ImageDraw, ImageFont
import json

# 单词数据
words_data = {
    "animals": [
        {"word": "cat", "chinese": "猫"},
        {"word": "dog", "chinese": "狗"},
        {"word": "bird", "chinese": "鸟"},
        {"word": "fish", "chinese": "鱼"},
        {"word": "rabbit", "chinese": "兔子"},
        {"word": "tiger", "chinese": "老虎"},
        {"word": "lion", "chinese": "狮子"},
        {"word": "elephant", "chinese": "大象"}
    ],
    "fruits": [
        {"word": "apple", "chinese": "苹果"},
        {"word": "banana", "chinese": "香蕉"},
        {"word": "orange", "chinese": "橙子"},
        {"word": "grape", "chinese": "葡萄"},
        {"word": "strawberry", "chinese": "草莓"},
        {"word": "watermelon", "chinese": "西瓜"},
        {"word": "pear", "chinese": "梨"},
        {"word": "peach", "chinese": "桃子"}
    ],
    "colors": [
        {"word": "red", "chinese": "红色"},
        {"word": "blue", "chinese": "蓝色"},
        {"word": "green", "chinese": "绿色"},
        {"word": "yellow", "chinese": "黄色"},
        {"word": "orange", "chinese": "橙色"},
        {"word": "purple", "chinese": "紫色"},
        {"word": "pink", "chinese": "粉色"},
        {"word": "black", "chinese": "黑色"}
    ],
    "numbers": [
        {"word": "one", "chinese": "一"},
        {"word": "two", "chinese": "二"},
        {"word": "three", "chinese": "三"},
        {"word": "four", "chinese": "四"},
        {"word": "five", "chinese": "五"},
        {"word": "six", "chinese": "六"},
        {"word": "seven", "chinese": "七"},
        {"word": "eight", "chinese": "八"},
        {"word": "nine", "chinese": "九"},
        {"word": "ten", "chinese": "十"}
    ]
}

# 颜色映射（用于生成颜色占位图）
color_map = {
    "red": "#FF0000",
    "blue": "#0000FF",
    "green": "#00FF00",
    "yellow": "#FFFF00",
    "orange": "#FFA500",
    "purple": "#800080",
    "pink": "#FFC0CB",
    "black": "#000000"
}

# 创建图片目录
images_dir = 'images/words'
os.makedirs(images_dir, exist_ok=True)

def download_image_from_url(url, filepath):
    """从URL下载图片"""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
        response = requests.get(url, headers=headers, timeout=10)
        if response.status_code == 200:
            with open(filepath, 'wb') as f:
                f.write(response.content)
            return True
    except Exception as e:
        print(f"  下载失败: {e}")
    return False

def download_from_unsplash(word, filepath, api_key=None):
    """从 Unsplash 下载图片（需要API key）"""
    if not api_key:
        return False
    
    try:
        url = f"https://api.unsplash.com/search/photos"
        params = {
            'query': word,
            'per_page': 1,
            'client_id': api_key
        }
        response = requests.get(url, params=params, timeout=10)
        if response.status_code == 200:
            data = response.json()
            if data.get('results') and len(data['results']) > 0:
                image_url = data['results'][0]['urls']['small']
                return download_image_from_url(image_url, filepath)
    except Exception as e:
        print(f"  Unsplash API 错误: {e}")
    return False

def download_from_pixabay(word, filepath, api_key=None):
    """从 Pixabay 下载图片（需要API key）"""
    if not api_key:
        return False
    
    try:
        url = "https://pixabay.com/api/"
        params = {
            'key': api_key,
            'q': word,
            'image_type': 'photo',
            'per_page': 1,
            'safesearch': 'true'
        }
        response = requests.get(url, params=params, timeout=10)
        if response.status_code == 200:
            data = response.json()
            if data.get('hits') and len(data['hits']) > 0:
                image_url = data['hits'][0]['webformatURL']
                return download_image_from_url(image_url, filepath)
    except Exception as e:
        print(f"  Pixabay API 错误: {e}")
    return False

def create_placeholder_image(word, chinese, filepath, category=None):
    """创建占位图（不需要API）"""
    # 图片尺寸
    width, height = 400, 400
    
    # 创建图片
    if category == 'colors' and word in color_map:
        # 颜色类：使用纯色背景，不添加任何文字
        bg_color = color_map[word]
        img = Image.new('RGB', (width, height), color=bg_color)
        # 直接保存纯色图片
        img.save(filepath, 'PNG')
        return True
    else:
        # 其他类：使用渐变背景
        img = Image.new('RGB', (width, height), color='#F0F0F0')
        draw = ImageDraw.Draw(img)
        # 绘制渐变背景
        for i in range(height):
            r = int(240 - i * 0.1)
            g = int(240 - i * 0.1)
            b = int(250 - i * 0.1)
            draw.line([(0, i), (width, i)], fill=(r, g, b))
    
    draw = ImageDraw.Draw(img)
    
    # 添加文字
    try:
        # 尝试使用系统字体
        font_large = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 60)
        font_small = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 40)
    except:
        font_large = ImageFont.load_default()
        font_small = ImageFont.load_default()
    
    # 绘制英文单词
    bbox = draw.textbbox((0, 0), word.upper(), font=font_large)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    x = (width - text_width) // 2
    y = height // 2 - text_height - 20
    
    # 绘制文字阴影
    draw.text((x + 2, y + 2), word.upper(), font=font_large, fill='#000000')
    draw.text((x, y), word.upper(), font=font_large, fill='#FFFFFF')
    
    # 绘制中文
    bbox = draw.textbbox((0, 0), chinese, font=font_small)
    text_width = bbox[2] - bbox[0]
    x = (width - text_width) // 2
    y = height // 2 + 20
    
    draw.text((x + 2, y + 2), chinese, font=font_small, fill='#000000')
    draw.text((x, y), chinese, font=font_small, fill='#FFFFFF')
    
    # 保存图片
    img.save(filepath, 'PNG')
    return True

def download_from_free_images(word, filepath):
    """从免费图片网站下载（使用公开API）"""
    # 使用 Picsum Photos（随机图片，仅作为占位符）
    # 注意：这不是真正的单词图片，只是占位符
    try:
        url = f"https://picsum.photos/400/400?random={hash(word)}"
        return download_image_from_url(url, filepath)
    except:
        return False

def process_word(word_info, category, method='placeholder', api_keys=None, force=False):
    """处理单个单词"""
    word = word_info['word']
    chinese = word_info['chinese']
    
    # 处理特殊文件名
    if word == 'orange' and category == 'colors':
        filename = 'orange-color.png'
    else:
        filename = f"{word}.png"
    
    filepath = os.path.join(images_dir, filename)
    
    # 如果文件已存在且不强制重新生成，跳过
    if os.path.exists(filepath) and not force:
        print(f"  ✓ {word} ({chinese}) - 已存在，跳过")
        return True
    
    print(f"  处理: {word} ({chinese})...", end=' ')
    
    success = False
    
    if method == 'unsplash' and api_keys and api_keys.get('unsplash'):
        success = download_from_unsplash(word, filepath, api_keys['unsplash'])
    elif method == 'pixabay' and api_keys and api_keys.get('pixabay'):
        success = download_from_pixabay(word, filepath, api_keys['pixabay'])
    elif method == 'placeholder':
        success = create_placeholder_image(word, chinese, filepath, category)
    elif method == 'free':
        success = download_from_free_images(word, filepath)
    
    if success:
        print("✓ 成功")
        return True
    else:
        print("✗ 失败")
        return False

def main():
    print("=" * 60)
    print("单词图片下载工具")
    print("=" * 60)
    print("\n可用方法：")
    print("1. placeholder - 生成占位图（不需要API，推荐）")
    print("2. unsplash - 从 Unsplash 下载（需要API key）")
    print("3. pixabay - 从 Pixabay 下载（需要API key）")
    print("4. free - 使用免费图片占位符（随机图片）")
    print("\n" + "=" * 60)
    
    # 选择方法
    method = input("\n请选择方法 (1-4，默认1): ").strip() or "1"
    method_map = {
        "1": "placeholder",
        "2": "unsplash",
        "3": "pixabay",
        "4": "free"
    }
    method = method_map.get(method, "placeholder")
    
    # 如果需要API key，提示输入
    api_keys = {}
    if method == 'unsplash':
        api_key = input("请输入 Unsplash API Key (留空跳过): ").strip()
        if api_key:
            api_keys['unsplash'] = api_key
        else:
            print("未提供 API key，将使用占位图方法")
            method = 'placeholder'
    elif method == 'pixabay':
        api_key = input("请输入 Pixabay API Key (留空跳过): ").strip()
        if api_key:
            api_keys['pixabay'] = api_key
        else:
            print("未提供 API key，将使用占位图方法")
            method = 'placeholder'
    
    print(f"\n使用方法: {method}")
    
    # 询问是否强制重新生成颜色类图片
    if method == 'placeholder':
        force_colors = input("是否强制重新生成颜色类图片？(y/n，默认n): ").strip().lower() == 'y'
    else:
        force_colors = False
    
    print(f"开始处理 {sum(len(words) for words in words_data.values())} 个单词...\n")
    
    # 处理所有单词
    success_count = 0
    total_count = 0
    
    for category, words in words_data.items():
        print(f"\n处理分类: {category}")
        force = force_colors and category == 'colors'
        for word_info in words:
            total_count += 1
            if process_word(word_info, category, method, api_keys, force):
                success_count += 1
            time.sleep(0.5)  # 避免请求过快
    
    print("\n" + "=" * 60)
    print(f"完成！成功: {success_count}/{total_count}")
    print(f"图片保存在: {images_dir}/")
    print("=" * 60)

if __name__ == '__main__':
    main()

